<template>
  <div ref="container" class="overflow-auto relative" @scroll="onScroll">
    <slot />
    <div v-if="loading" class="text-center py-2 text-gray-500">加载中...</div>
    <div v-if="finished" class="text-center py-2 text-gray-400">没有更多了</div>
  </div>
</template>
<style scoped lang="scss">
.text-center{
  display: flex;
  justify-content: center;
  font-size: 14px;
  color: #999;
}
.overflow-auto{
  overflow-y: auto;
  height: calc(100% - 45px);
  box-sizing: border-box;
  padding-bottom: 60px;
}
</style>

<script setup>
import { ref, watch, nextTick, onMounted } from 'vue'

const props = defineProps({
  loading: Boolean,
  finished: Boolean,
  immediate: Boolean,
  threshold: {
    type: Number,
    default: 100
  },
  fillFirstPage: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['load'])
const container = ref(null)

const check = () => {
  if (props.loading || props.finished) return

  const el = container.value
  if (!el) return

  const distance = el.scrollHeight - el.scrollTop - el.clientHeight

  if (distance < props.threshold) {
    emit('load')
  }
}

// 关键逻辑：尝试填满容器（初始加载不足时）
const tryFill = async () => {
  await nextTick()
  const el = container.value
  if (!el || props.finished) return

  // 如果内容高度小于容器高度，继续触发加载
  if (el.scrollHeight <= el.clientHeight) {
    emit('load')
  }
}

const onScroll = () => {
  check()
}

watch(() => props.loading, (val) => {
  if (!val && props.fillFirstPage) {
    tryFill()
  }
})

onMounted(() => {
  if (props.immediate) {
    check()
  }
  if (props.fillFirstPage) {
    tryFill()
  }
})
</script>
